//index.js
//获取应用实例
const app = getApp()

Page({
  data: {   
    currentData: 0,
    subjects: [],
    subject_id: 0,
    dataList:[]
  },
  onLoad: function () { 
    wx.showLoading({
      title: '加载中',
    })  
    //获取所有课程
    wx.request({
      url: 'https://sng.tsletu.com/api/wxapp/subject',
      header: {
        'XX-Device-Type': 'wxapp',
        'XX-Token': app.globalData.token
      },
      success: res => {        
        this.setData({
          subjects: res.data.data,
          subject_id: res.data.data[0].id          
        })
        this.getCourses(this.data.subject_id) 
      }
    })
    wx.hideLoading()
  },  
  //点击切换，滑块index赋值
  checkCurrent: function (e) {
    wx.showLoading({
      title: '加载中',
    }) 

    const that = this;
    if (that.data.currentData === e.target.dataset.current) {
      return false;
    } else {
      that.setData({
        currentData: e.target.dataset.current,
        subject_id: e.target.dataset.id
      })
      this.getCourses(that.data.subject_id) 
    }  
    wx.hideLoading()
  },
  getCourses: function (subject_id){
    //获取课程
    wx.request({
      url: 'https://sng.tsletu.com/api/wxapp/course',
      header: {
        'XX-Device-Type': 'wxapp',
        'XX-Token': app.globalData.token
      },
      data: {
        subject_id: subject_id
      },
      success: res => {
        this.setData({
          dataList: res.data.data
        })        
      }
    })
  },
  toAllCourse: function (e) {
    wx.navigateTo({
      url: '/pages/course/index'
    })
  },
  toDetail: function (e) {
    wx.navigateTo({
      url: '/pages/detail/index?id=' + e.currentTarget.id
    })
  },  
  onPullDownRefresh: function () {
    wx.showLoading({
      title: '加载中',
    })
    this.getCourses(this.data.subject_id) 
    wx.stopPullDownRefresh()
    wx.hideLoading();
  }
})
